console.log('popup.js');
const baseUrl = 'https://api.yi-ja.com/';
// 获取background.js
let bg = chrome.extension.getBackgroundPage();

let app = new Vue({
    el: '#app',
    // 数据
    data: {
        site: {
            title: '小方格',
            company: '易加软件',
            url: 'http://yi-ja.com/',
        },
        sync: false,
        text: {
            check: '验证',
            sync: '同步',
            syncStart: '同步中...',
            out: '退出',
        },
        login: {
            account: '',
            password: '',
        },
        key: '',
        token: '',
        info: '',
    },
    created() {
        this.key = localStorage.getItem('key') || '';
        this.token = localStorage.getItem('token') || '';
        this.info = localStorage.getItem('info') && JSON.parse(localStorage.getItem('info')) ? JSON.parse(localStorage.getItem('info')) : '';
        if(this.token){
            this.checkToken();
        }
    },
    // 方法
    methods: {
        // 新窗口打开页面
        tabsHref() {
            let that = this;
            chrome.tabs.create({url: that.site.url});
        },
        // 获取KEY
        getKey(call) {
            let key = this.key;
            if (!key) {
                bg.notice('无key值');
            } else {
                if (call) {
                    call(key);
                } else {
                    console.log('no callback function')
                }
            }
        },
        // 检查key
        checkKey() {
            let that = this;
            that.getKey(function (key) {
                // 发送请求
                axios({
                    method: 'get',
                    url: baseUrl + 'nav/checkKey',
                    params: {
                        key: key,
                    }
                }).then(rps => {
                    let res = rps.data;
                    if (res.code == 0) {
                        localStorage.setItem('key', key);
                        bg.notice(res.msg);
                    } else {
                        bg.notice(res.msg);
                    }
                }).catch(err => {
                    console.log(err);
                });
            })
        },
        // 获取Token
        getToken(call) {
            let val = this.token;
            if (!val) {
                bg.notice('登录已失效');
                this.clearAccountPassword();
            } else {
                call && call(val);
            }
        },
        // 验证Token
        checkToken(call) {
            let that = this;
            that.getToken(function (token) {
                console.log('checkToken', token);
                // 发送请求
                axios({
                    method: 'get',
                    url: baseUrl + 'user/checkToken',
                    params: {
                        token: token
                    }
                }).then(rps => {
                    let res = rps.data;
                    if (res.code == 0) {
                        call && call(token);
                    } else {
                        that.token = '';
                        bg.clearStorage();
                        bg.notice(res.msg);
                    }
                }).catch(err => {
                    console.log(err);
                });
            })
        },
        // 同步书签
        syncBookmark() {
            let that = this;
            that.checkToken(function (token) {
                that.sync = true;
                that.bookmark(token);
            });
        },
        // 书签
        bookmark(token) {
            let that = this;
            chrome.bookmarks.getTree(tree => {
                console.log('tree->', tree);
                let json = JSON.stringify(tree);
                if (tree.length) {
                    // 发送请求
                    axios({
                        method: 'post',
                        url: baseUrl + 'nav/importTree',
                        data: {
                            token: token,
                            json: json,
                        },
                        transformRequest: [function (data) {
                            // 对 data 进行任意转换处理
                            let str = '';
                            for (const key in data) {
                                str += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
                            }
                            return str.slice(0, str.length - 1);
                        }],
                    }).then(rps => {
                        //console.log('request', rps);
                        that.sync = false;
                        let res = rps.data;
                        bg.notice(res.msg);
                    }).catch(err => {
                        console.log(err);
                    });
                } else {
                    alert('您还没有书签,无法进行该操作');
                }
            });
        },
        // 获取key
        getNavKey(token, call) {
            let that = this;
            // 发送请求
            axios({
                method: 'get',
                url: baseUrl + 'user/getNavKey',
                params: {
                    token: token,
                }
            }).then(rps => {
                console.log(rps);
                let res = rps.data,
                    code = res.code,
                    msg = res.msg;
                if (code == 0) {
                    call(res.key);
                } else {
                    that.out();
                    bg.notice(msg);
                }
            }).catch(err => {

            })
        },
        // 获取信息
        getInfo(token, call) {
            let that = this;
            // 发送请求
            axios({
                method: 'get',
                url: baseUrl + 'user/getInfo',
                params: {
                    token: token,
                }
            }).then(rps => {
                let res = rps.data,
                    code = res.code,
                    msg = res.msg;
                if (code == 0) {
                    call(res.info);
                } else {
                    that.out();
                    bg.notice(msg);
                }
            }).catch(err => {

            })
        },
        // 登录
        loginBtn() {
            let that = this,
                data = that.login,
                account = data.account,
                password = data.password;
            if (!account) {
                bg.notice('账号必填');
                return false;
            }
            if (!password) {
                bg.notice('密码必填');
                return false;
            }
            console.log('loginBtn', data);
            // 发送请求
            axios({
                method: 'post',
                url: baseUrl + 'user/login',
                data: 'account=' + account + '&password=' + password
            }).then(rps => {
                let res = rps.data,
                    code = res.code,
                    msg = res.msg;
                if (code == 0) {
                    let token = res.token;
                    that.token = token;
                    localStorage.setItem('token', token);
                    // 用户信息
                    that.getInfo(token, info => {
                        that.info = info;
                        localStorage.setItem('info', JSON.stringify(info));
                    })
                    // 口令
                    that.getNavKey(token, key => {
                        that.key = key;
                        localStorage.setItem('key', key);
                        bg.initContentMenus();
                    });
                    that.clearAccountPassword();
                }
                bg.notice(msg);
            }).catch(err => {
                console.log(err);
            });
        },
        // 退出
        out() {
            let that = this,
                token = that.token;
            // 发送请求
            axios({
                method: 'post',
                url: baseUrl + 'user/out',
                data: 'token=' + token
            }).then(rps => {
                let res = rps.data,
                    code = res.code,
                    msg = res.msg;

                // 清理右键菜单和缓存
                bg.clearContentMenus();
                bg.clearStorage();
                that.token = '';
                that.key = '';
                that.info = '';
                bg.notice(msg);
            }).catch(err => {
                console.log(err);
            });
        },
        // 清理账号密码
        clearAccountPassword() {
            this.login = {
                account: '',
                password: '',
            }
        },
    },
    // 动态监听
    watch: {
        key(val) {
            this.key = val.toUpperCase();
        }
    }
});
